package com.ebei.admin.common.util;

import com.ebei.common.constant.CommonConstant;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.apache.commons.lang.time.DateUtils;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.*;

/**
 * 通过泛型和反射自动Mapper数据
 * <p>Title: ConvertUtil.java</p>
 * <p>Description: </p>
 *
 * @author Fbb
 * @version 1.0
 */
public class ConvertUtil {

    static {
        //设置时间转换
        ConvertUtils.register(new Converter() {
            public Object convert(Class type, Object value) {
                try {
                    return CommonConstant.Y2S.parse(value.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }, Date.class);
    }

    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null)
            return null;

        Object obj = beanClass.newInstance();

        BeanUtils.populate(obj, map);

        return obj;
    }

    public static Map<?, ?> objectToMap(Object obj) {
        if (obj == null)
            return null;
        return new BeanMap(obj);
    }

    public static List<Object> convertList(List<Map<String, Object>> list, Class target) throws Exception {
        List result = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Object t = target.newInstance();
            BeanUtils.populate(t, map);
            result.add(t);
        }
        return result;
    }

    public static List<Map<String, Object>> convertList(List<?> list) throws Exception {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Object o : list) {
            result.add(objectToMap2(o));
        }
        return result;
    }

    public static Map<String, Object> objectToMap2(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }

        return map;
    }
}
